package com.winit.schedule.job.tracker.repository.mongo;

import java.util.List;

import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.winit.schedule.core.model.JobID;
import com.winit.schedule.core.repository.JobRepository;
import com.winit.schedule.core.repository.constants.JobStatus;
import com.winit.schedule.core.repository.entity.JobEntity;
import com.winit.schedule.core.utils.Clock;
import com.winit.schedule.store.mongo.AbstractMongoRepository;

public class MongoJobRepository extends AbstractMongoRepository<JobEntity> implements JobRepository {

    @Override
    public JobEntity saveJob(JobEntity job) {
        Query<JobEntity> query = createQuery().field("jobId.jobId").equal(job.getJobId().getJobId());
        UpdateOperations<JobEntity> ops = ds.createUpdateOperations(JobEntity.class)
            .disableValidation()
            .set("jobId", job.getJobId())
            .set("jobName", null == job.getJobName() ? "" : job.getJobName())
            .set("createTime", job.getCreateTime())
            .set("immediatelyRun", job.isImmediatelyRun())
            .set("runStartTime", job.getRunStartTime())
            .set("runEndTime", null == job.getRunEndTime() ? "" : job.getRunEndTime())
            .set("jobStatus", job.getJobStatus())
            .set("lastUpdateTime", Clock.getSystemTime());

        ops.set("remark", null != job.getRemark() ? job.getRemark() : "");
        if (null != job.getJobTrackerGroup()) {
            ops.set("jobTrackerGroup", job.getJobTrackerGroup());
        }
        return ds.findAndModify(query, ops, false, true);
    }

    @Override
    public void removeJob(JobID jobId) {
        Query<JobEntity> query = createQuery().field("jobId.jobId").equal(jobId.getJobId());
        ds.delete(query);
    }

    @Override
    public void updateJobStatus(JobID jobId, JobStatus status) {
        if (null != status) {
            Query<JobEntity> query = createQuery().field("jobId.jobId").equal(jobId.getJobId());
            UpdateOperations<JobEntity> ops = ds.createUpdateOperations(JobEntity.class);
            ops.set("jobStatus", status);
            ops.set("lastUpdateTime", Clock.getSystemTime());
            ds.update(query, ops);
        }
    }

    @Override
    public List<JobEntity> queryAllJobs() {
        Query<JobEntity> query = createQuery();
        return query.asList();
    }

    @Override
    public JobEntity queryJobById(String jobId) {
        Query<JobEntity> query = createQuery().field("jobId.jobId").equal(jobId);
        return query.get();
    }

}
